package com.xiaoshuidi.cloud.module.finance.mq.consumer;

import com.xiaoshuidi.cloud.framework.common.core.KeyValue;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.hangxin.core.dto.InvoicingRespDTO;
import com.xiaoshuidi.cloud.framework.hangxin.core.service.InvoiceService;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.invoice.FinanceInvoiceConfigDO;
import com.xiaoshuidi.cloud.module.finance.dal.dataobject.invoice.FinanceInvoiceRecordDO;
import com.xiaoshuidi.cloud.module.finance.enums.invoice.InvoicingStatusEnum;
import com.xiaoshuidi.cloud.module.finance.service.invoice.FinanceInvoiceConfigService;
import com.xiaoshuidi.cloud.module.finance.service.invoice.FinanceInvoiceRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

@Slf4j
@Component("invoiceQueryDelay")
public class InvoiceQueryDelayConsumer implements Consumer<KeyValue<String, String>> {
    @Resource
    private FinanceInvoiceRecordService financeInvoiceRecordService;
    @Resource
    private FinanceInvoiceConfigService financeInvoiceConfigService;
    @Resource
    private InvoiceService invoiceService;
    private Map<Integer, FinanceInvoiceConfigDO> config = new ConcurrentHashMap<>(1);
    private DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    @Override
    public void accept(KeyValue<String, String> seqNo) {
        log.info("查询开票结果: {}", seqNo);
        FinanceInvoiceRecordDO record = financeInvoiceRecordService.getBySeqNo(seqNo.getValue());
        if (record == null) {
            log.info("开票记录不存在: {}", seqNo);
            return;
        }
        FinanceInvoiceConfigDO configDO = config.get(record.getInvoiceConfigId());
        if (configDO == null) {
            configDO = financeInvoiceConfigService.getById(record.getInvoiceConfigId());
            config.put(configDO.getId(), configDO);
        }
        try {
            InvoicingRespDTO respDTO = invoiceService.query(configDO.getCompanyTaxpayerId(), configDO.getHangxinAuthCode(), seqNo.getValue());
            // 0|1|2|3|4|5 未开票|开票中|开票成功|开票失败|申请成功|申请失败
            if ("2".equals(respDTO.getFP_STATUS())) {
                financeInvoiceRecordService.updateById(FinanceInvoiceRecordDO.builder()
                        .id(record.getId())
                        .taxDeviceNo(respDTO.getJQBH())
                        .invoiceCode(respDTO.getFP_DM())
                        .invoiceNo(respDTO.getFP_HM())
                        .createDate(LocalDateTime.parse(respDTO.getKPRQ(), fmt))
                        .ciphertext(respDTO.getFP_MW())
                        .qrCode(respDTO.getEWM())
                        .checkCode(respDTO.getJYM())
                        .pdfUrl(respDTO.getPDF_URL())
                        .status(InvoicingStatusEnum.SUCCESS.name())
                        .build());
            } else if (!"1|4".contains(respDTO.getFP_STATUS())) {
                log.info("查询开票结果: {}/[{}][{}]", seqNo, respDTO.getFP_STATUS(), respDTO.getERROR_MSG());
                financeInvoiceRecordService.updateById(FinanceInvoiceRecordDO.builder()
                        .id(record.getId())
                        .status(InvoicingStatusEnum.FAILURE.name())
                        .build());
            }
        } catch (ServiceException e) {
            log.info("查询开票接口返回错误 {}", e.getMessage());
        }
    }
}
